﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace Manyor.Net
{
    /// <summary>
    /// Socket接受对象
    /// </summary>
    public class SocketServer
    {
        #region -- Events
        /// <summary>
        /// 网络连接状态发生改变
        /// </summary>
        public event EventHandler OnConnectStateChanged;
        /// <summary>
        /// 网络错误
        /// </summary>
        public event EventHandler OnNetError;        
        #endregion

        #region -- Const --
        //private const int PORT = 4021;
        #endregion

        #region -- Private --
        private IPEndPoint ipep;
        private Socket serverSocket;
        private Socket accepedSocket;
        private Byte[] buffer = new Byte[NetConfig.BUFFER_SIZE];
        #endregion

        private Action<byte[], int> ReceiveBytesDelegate;
        /// <summary>
        /// 构造函数,指定需要一个 Action 委托方法，接受消息
        /// </summary>
        /// <param name="action"></param>
        public SocketServer(Action<byte[], int> action)
        {
            if (action != null)
            {
                ReceiveBytesDelegate = action;
            }
        }
        /// <summary>
        /// 启动监听
        /// </summary>
        public bool StartServer()
        {
            try
            {
                ipep = new IPEndPoint(IPAddress.Any, NetConfig.PORT_SERVER);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(ipep);
                serverSocket.Listen(2);
                serverSocket.BeginAccept(new AsyncCallback(AcceptAsync), serverSocket);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 接受链接
        /// </summary>
        /// <param name="arg"></param>
        private void AcceptAsync(IAsyncResult arg)
        {            
            accepedSocket = serverSocket.EndAccept(arg);
            //发送连接OK信号
            accepedSocket.Send(BitConverter.GetBytes(CommandCode.COMMAND_CONNECT_OK));
            //接收客户端的消息
            accepedSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), accepedSocket);
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="ar"></param>
        public void ReceiveMessage(IAsyncResult ar)
        {
            var socket = ar.AsyncState as Socket;
            var length = socket.EndReceive(ar);            
            //var message = Encoding.UTF8.GetString(buffer, 0, length);
            //返回结果
            if (ReceiveBytesDelegate != null)
            {
                ReceiveBytesDelegate(buffer, length);
            }
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
        }

        /// <summary>
        /// 发送消息，返回发送结果
        /// </summary>
        /// <param name="bytes">待发送的字节数组</param>
        /// <returns></returns>
        public bool SendMessage(byte[] bytes)
        {
            if (accepedSocket!=null && accepedSocket.Connected)
            {
                try
                {
                    accepedSocket.Send(bytes);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
                return false;
        }
    }
}
